<template>
  <fks-cascader
    v-if="multiPortal"
    ref="cascader"
    v-model="chosedPortal"
    :options="portalTreeForShow"
    :show-all-levels="false"
    :props="{
      checkStrictly: true,
      value: 'id',
      label: 'name'
    }"
    :disabled="!isMainPortal"
    popper-class="portal-popper-cascader"
    @change="handleChange"
  >
  </fks-cascader>
</template>

<script>
import { AUTH_PORTAL } from '@/store/Getter/getterTypes.js'
import { UPDATE_AUTH_PORTAL } from '@/store/Mutation/mutationTypes'
export default {
  name: 'PortalSelector',
  data() {
    return {
      chosedPortal: [], //当前树形选择器中选中的门户
      portalLevel: '',
      portalId: ''
    }
  },
  computed: {
    /* 下拉的门户树，一级为门户等级，二级为具体门户 */
    portalTreeForShow() {
      let arr = this.portalTypes.filter((item) => {
        item.name = item[this.$lang]
        item.id = item.code
        item.children = this.$store.state.portals.filter((portal) => {
          return portal.type == item.code
        })
        if (item.children.length <= 0) {
          delete item.children
        }
        return true
      })

      return arr
    },
    /* 门户等级列表 */
    portalTypes() {
      return this.$store.state.enum.portalType || []
    },
    /* 当前门户 */
    portal() {
      return this.$store.state.portal
    },
    /* 多门户开关是否开启 */
    multiPortal() {
      return this.$store.getters.multiPortal
    },
    /**
     * @description: 是否一级门户，该级门户下才可跨门户切换，否则锁死为自己
     */
    isMainPortal() {
      return this.portal.type == 1
    },
    /* 正在编辑的门户的等级和id */
    authPortal() {
      let type = this.chosedPortal[0]
      let length = this.chosedPortal.length
      let portalId = length > 1 ? this.chosedPortal[length - 1] : ''

      return {
        type,
        portalId
      }
    }
  },
  watch: {
    authPortal: {
      deep: true,
      handler: function () {
        if (!this.multiPortal || !this.authPortal.type) {
          return
        }
        this.$store.commit(UPDATE_AUTH_PORTAL, this.authPortal)
        this.$emit('change', this.authPortal)
      }
    }
  },
  methods: {
    /**
     * @description: 手动选择节点后关闭下拉并回调
     */
    handleChange(node) {
      this.$refs.cascader.dropDownVisible = false
    }
  },
  mounted() {
    if (!this.multiPortal) {
      this.$store.commit(UPDATE_AUTH_PORTAL, {})
      return
    }
    this.chosedPortal = Object.values(this.$store.getters[AUTH_PORTAL]) || []
  }
}
</script>

<style>
</style>
